package com.lovezy.platform.core.valid.validators;


import com.lovezy.platform.core.exception.ValidationException;
import com.lovezy.platform.core.valid.Validator;
import com.lovezy.platform.core.valid.annotation.NumberFormat;

import java.lang.annotation.Annotation;
import java.text.DecimalFormat;

/**
 * 数字格式校验器 (只处理double和float类型的数据)
 *
 */
public class NumberFormatValidator implements Validator {

	@Override
	public void validate(Object value, Annotation annotation)
			throws ValidationException {

		if (!(value instanceof Double) && !(value instanceof Float)) {
			return;
		}

		NumberFormat nf = (NumberFormat) annotation;
		DecimalFormat format = new DecimalFormat(nf.format());

		double newd = Double.valueOf(format.format(value));
		if (newd != Double.valueOf(value.toString())) {
			throw new ValidationException(nf.errorCode(), nf.errorMsg());
		}
	}

}
